package com.example.orchid.paper.fragment;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.orchid.paper.Constants;
import com.example.orchid.paper.PaperApplication;
import com.example.orchid.paper.R;
import com.example.orchid.paper.activity.NewsDetailActivity;
import com.example.orchid.paper.adapter.NewsAdapter;
import com.example.orchid.paper.db.NewsDataSource;
import com.example.orchid.paper.entity.NewsListEntity;
import com.example.orchid.paper.entity.NewsListEntity.NewsEntity;
import com.example.orchid.paper.task.BaseGetNewsTask;
import com.example.orchid.paper.task.BaseGetNewsTask.ResponseListener;
import com.example.orchid.paper.task.GetLatestNewsTask;
import com.example.orchid.paper.task.MyAsyncTask;
import com.example.orchid.paper.util.GsonUtils;
import com.example.orchid.paper.util.ListUtils;
import com.example.orchid.paper.util.ZhihuUtils;

import java.io.IOException;
import java.util.ArrayList;

/**
 * NewsListFragment
 * Created by Orchid on 2015-10-12.
 */
public class NewsListFragment extends BaseFragment implements OnRefreshListener, ResponseListener, AdapterView.OnItemClickListener {
    private ListView mListView;

    private SwipeRefreshLayout mSwipeLayout;
    private ArrayList<NewsEntity> mNewsList = null;
    //上次listView滚动到最下方时，itemId
    private int mListViewPreLast = 0;
    private String mCurrentDate = null;

    private NewsAdapter mAdapter = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new LoadCacheNewsTask().executeOnExecutor(MyAsyncTask.THREAD_POOL_EXECUTOR);

        new GetLatestNewsTask(getActivity(), this).executeOnExecutor(MyAsyncTask.THREAD_POOL_EXECUTOR);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);


        mSwipeLayout = (SwipeRefreshLayout) view;
        mSwipeLayout.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources()
                        .getDisplayMetrics()));
        mSwipeLayout.setOnRefreshListener(this);
        mSwipeLayout.setColorSchemeResources(android.R.color.holo_green_dark, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);

        mListView = (ListView) view.findViewById(R.id.list);
        mListView.setOnItemClickListener(this);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                final int lastItem = firstVisibleItem + visibleItemCount;
                if (lastItem == totalItemCount) {
                    if (mListViewPreLast != lastItem) { // to avoid multiple calls for

                        mCurrentDate = ZhihuUtils.getBeforeDate(mCurrentDate);

                        new GetMoreNewsTask(getActivity(), null).executeOnExecutor(MyAsyncTask.THREAD_POOL_EXECUTOR, mCurrentDate);

                        mListViewPreLast = lastItem;
                    }
                }
            }
        });
    }

    private void setAdapter(ArrayList<NewsEntity> newsList) {
        if (mAdapter == null) {
            mAdapter = new NewsAdapter(getActivity(), newsList);
            mListView.setAdapter(mAdapter);
        } else {
            mAdapter.updateData(newsList);
        }
    }

    private void setListShown(boolean isListViewShown) {
        mListView.setVisibility(isListViewShown ? View.VISIBLE : View.GONE);
        mSwipeLayout.setRefreshing(!isListViewShown);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        NewsEntity newsEntity = mNewsList != null ? mNewsList.get(position) : null;

        if (newsEntity == null) {
            return;
        }

        Intent intent = new Intent();
        intent.putExtra("id", newsEntity.id);
        intent.putExtra("newsEntity", newsEntity);

        intent.setClass(getActivity(), NewsDetailActivity.class);
        startActivity(intent);

        new SetReadFlagTask(newsEntity).executeOnExecutor(MyAsyncTask.THREAD_POOL_EXECUTOR);
    }

    //读取缓存中的最新新闻
    private class LoadCacheNewsTask extends MyAsyncTask<String, Void, NewsListEntity> {

        @Override
        protected NewsListEntity doInBackground(String... params) {

            NewsListEntity latestNewsEntity = PaperApplication.getDataSource().getLatestNews();

            if (latestNewsEntity != null) {
                mCurrentDate = latestNewsEntity.date;
                ZhihuUtils.setReadStatus4NewsList(latestNewsEntity.stories);
            }

            return latestNewsEntity;
        }

        @Override
        protected void onPostExecute(NewsListEntity result) {
            super.onPostExecute(result);

            if (!isAdded())
                return;

            if (result != null && !ListUtils.isEmpty(result.stories)) {

                NewsEntity tagNewsEntity = new NewsEntity();
                tagNewsEntity.isTag = true;
                tagNewsEntity.title = result.date;

                mNewsList = new ArrayList<NewsEntity>();
                mNewsList.add(tagNewsEntity);
                mNewsList.addAll(result.stories);

                setAdapter(mNewsList);
            }
        }
    }

    private class GetMoreNewsTask extends BaseGetNewsTask {

        public GetMoreNewsTask(Context context, ResponseListener listener) {
            super(context, listener);
        }

        @Override
        protected NewsListEntity doInBackground(String... params) {

            if (params.length == 0)
                return null;

            String theKey = params[0];

            String oldContent = ((NewsDataSource) getDataSource()).getContent(theKey);

            NewsListEntity newsListEntity = null;

            if (!TextUtils.isEmpty(oldContent)) {
                newsListEntity = (NewsListEntity) GsonUtils.getEntity(oldContent, NewsListEntity.class);
                if (newsListEntity != null) {
                    ZhihuUtils.setReadStatus4NewsList(newsListEntity.stories);
                }
                return newsListEntity;
            } else {

                String newContent = null;

                try {
                    newContent = getUrl(Constants.Url.URLDEFORE + ZhihuUtils.getAddedDate(theKey));

                    newsListEntity = (NewsListEntity) GsonUtils.getEntity(newContent, NewsListEntity.class);

                    isRefreshSuccess = !ListUtils.isEmpty(newsListEntity.stories);
                } catch (IOException e) {
                    e.printStackTrace();

                    this.isRefreshSuccess = false;
                    this.mException = e;
                } catch (Exception e) {
                    e.printStackTrace();

                    this.isRefreshSuccess = false;
                    this.mException = e;
                }

                isContentSame = checkIsContentSame(oldContent, newContent);

                if (isRefreshSuccess && !isContentSame) {
                    ((NewsDataSource) getDataSource()).insertOrUpdateNewsList(Constants.NEWS_LIST, theKey, newContent);
                }

                if (newsListEntity != null) {
                    ZhihuUtils.setReadStatus4NewsList(newsListEntity.stories);
                }

                return newsListEntity;
            }
        }

        @Override
        protected void onPostExecute(NewsListEntity result) {
            super.onPostExecute(result);

            if (!isAdded())
                return;

            setListShown(true);

            mListViewPreLast = 0;

            if (mNewsList == null) {
                mNewsList = new ArrayList<NewsEntity>();
            }

            if (result != null && !ListUtils.isEmpty(result.stories)) {

                NewsEntity tagNewsEntity = new NewsEntity();
                tagNewsEntity.isTag = true;
                tagNewsEntity.title = result.date;
                mNewsList.add(tagNewsEntity);
                mNewsList.addAll(result.stories);

                setAdapter(mNewsList);
            }
        }
    }


    @Override
    public void onRefresh() {
// Hide the list
//        setListShown(!(mNewsList == null || mNewsList.isEmpty()));

        new GetLatestNewsTask(getActivity(), this).executeOnExecutor(MyAsyncTask.THREAD_POOL_EXECUTOR);

    }

    public void updateList() {
        new LoadCacheNewsTask().executeOnExecutor(MyAsyncTask.THREAD_POOL_EXECUTOR);
    }


    @Override
    protected void onRestoreState(Bundle savedInstanceState) {

    }

    @Override
    protected void onSaveState(Bundle outState) {

    }

    @Override
    protected void onFirstTimeLaunched() {

    }

    @Override
    public void onPreExecute() {

    }

    @Override
    public void onPostExecute(NewsListEntity result) {
        if (!isAdded()) {
            return;
        }

        mSwipeLayout.setRefreshing(true);

        if (getView() != null) {
            setListShown(true);
        }

        if (result != null) {
            mNewsList = new ArrayList<>();

            NewsEntity tagNewsEntity = new NewsEntity();
            tagNewsEntity.isTag = true;
            tagNewsEntity.title = result.date;
            mNewsList.add(tagNewsEntity);

            mNewsList.addAll(result.stories);

            mCurrentDate = result.date;

            setAdapter(mNewsList);
        }

    }

    @Override
    public void onProgressUpdate(String value) {

    }

    @Override
    public void onFail(Exception e) {
        if (getView() != null) {
            setListShown(true);
        }

    }

    private void dealException() {
        if (isAdded()) {
            mSwipeLayout.setRefreshing(true);
        }
    }


    private class SetReadFlagTask extends MyAsyncTask<String, Void, Boolean> {

        private NewsEntity mNewsEntity;

        public SetReadFlagTask(NewsEntity newsEntity) {
            mNewsEntity = newsEntity;
        }

        @Override
        protected Boolean doInBackground(String... params) {
            return PaperApplication.getNewsReadDataSource().readNews(String.valueOf(mNewsEntity.id));
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);

            if (aBoolean) {
                ZhihuUtils.setReadStatus4NewsEntity(mNewsList, mNewsEntity);
                mAdapter.updateData(mNewsList);
            }
        }
    }
}
